﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using invrt;
using Pibby.Core.Web;

namespace Pibby.Core.Tests.Stubs
{
	public class DownloadingService : IDownloadingService
	{
		#region Events

		public event EventHandler<ProgressEventArgs> DownloadProgressChanged;
		public event EventHandler<DownloadCompleteEventArgs> DownloadFileCompleted;
		public event EventHandler<DownloadCompleteEventArgs> DownloadDataCompleted;

		#endregion

		#region Attributes

		private bool _busy;
		private IGenerateContent _contentGenerator;

		#endregion

		#region Constructors

		public DownloadingService()
		{
			try
			{
				this._contentGenerator = InversionOfController.Factory.CreateTypeOf<IGenerateContent>();
			}
			catch (TypeNotRegisteredException)
			{
				// not registered - this is not critical for us
			}
		}

		public DownloadingService(IGenerateContent content)
		{
			this._contentGenerator = content;
		}

		public void Dispose()
		{
			// nothing !

		}

		#endregion

		#region Properties

		public bool Async
		{
			get;
			set;
		}

		public bool IsBusy
		{
			get { return this._busy; }
		}
		
		#endregion

		#region Methods

		public void Download(string source, string target)
		{
			this._busy = true;

			if (this.DownloadProgressChanged != null)
				this.DownloadProgressChanged(this, new ProgressEventArgs(0));

			//if (System.IO.File.Exists(target))
			//    System.IO.File.Delete(target);

			if (this.DownloadProgressChanged != null)
				this.DownloadProgressChanged(this, new ProgressEventArgs(10));

			System.Threading.Thread.Sleep(1000);

			if (this.DownloadProgressChanged != null)
				this.DownloadProgressChanged(this, new ProgressEventArgs(50));

			//if (this._contentGenerator != null)
			//{
			//    using (TextWriter writer = this._contentGenerator.)
			//    {
			//        writer.Write(this._contentGenerator.Content);
			//    }
			//}

			if (this.DownloadProgressChanged != null)
				this.DownloadProgressChanged(this, new ProgressEventArgs(75));

			System.Threading.Thread.Sleep(1000);

			this._busy = false;

			if (this.DownloadProgressChanged != null)
				this.DownloadProgressChanged(this, new ProgressEventArgs(100));

			if (this.DownloadFileCompleted != null)
				this.DownloadFileCompleted(this, new DownloadCompleteEventArgs ());
		}

		public string DownloadAsString(string source)
		{
			string content = string.Empty;

			if (this._contentGenerator != null)
			{
				content = this._contentGenerator.Content;
			}

			return content;
		}

		public byte[] DownloadData(string source)
		{
			string rssContent = Downloads[source];

			byte[] data = Encoding.UTF8.GetBytes(rssContent);

			return data;
		}

		#endregion


		public static Dictionary<string, string> Downloads = new Dictionary<string,string> ();
	}
}
